package com.skyable.device.config.mybatisplus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.skyable.device.config.CloudApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author GaoYuan
 * @date 2019/11/7 12:23
 * @desc
 */
@Configuration
public class MyBatisPlusConfig {

    /**
     * MybatisPlus分页插件
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        Map<String, TableNameHandler> map = new HashMap<String, TableNameHandler>(3) {{
            // metaObject 可以获取传入参数，这里实现你自己的动态规则
            put("device_info", (sql, tableName) -> CloudApplicationContext.domainId.get() + "_" + tableName);
            put("device_log", (sql, tableName) -> CloudApplicationContext.domainId.get() + "_" + tableName);
            put("bind_info", (sql, tableName) -> CloudApplicationContext.domainId.get() + "_" + tableName);
        }};
        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);

        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
